#include "imageview.h"

#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>

#include <QDebug>


ImageView::ImageView(QWidget *parent) :
    QGraphicsView(parent)
{
    m_scene = new QGraphicsScene(this);
    this->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    this->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

}

QImage ImageView::IplImage2QImage(const IplImage *iplImage){
    int height = iplImage->height;
    int width = iplImage->width;
    if  (iplImage->depth == IPL_DEPTH_8U && iplImage->nChannels == 3)
    {
        const uchar *qImageBuffer = (const uchar*)iplImage->imageData;
        QImage img(qImageBuffer, width, height, QImage::Format_RGB888);
        return img.rgbSwapped();
    } else if  (iplImage->depth == IPL_DEPTH_8U && iplImage->nChannels == 1){
        const uchar *qImageBuffer = (const uchar*)iplImage->imageData;
        QImage img(qImageBuffer, width, height, QImage::Format_Indexed8);

        QVector<QRgb> colorTable;
        for (int i = 0; i < 256; i++){
            colorTable.push_back(qRgb(i, i, i));
        }
        img.setColorTable(colorTable);
        return img;
    }else{
        return QImage();
    }
}

void ImageView::showImage(cv::Mat &img){
    this->m_mutex.lock();
    cv::Mat temp;
    img.copyTo(temp);
    cv::resize(temp, temp, cv::Size(this->width(), this->height()));
    temp.copyTo(this->m_img);
    IplImage _img = temp;
    QImage qimg = IplImage2QImage(&_img);
    m_scene->clear();
    m_scene->addPixmap(QPixmap::fromImage(qimg));
    this->setScene(m_scene);
    this->m_mutex.unlock();
}

void ImageView::showSelectedRect(cv::Point2i top_left, cv::Point2i bottom_right, cv::Scalar color){
    this->m_mutex.lock();
    if(!this->m_img.empty()){
        cv::Mat temp;
        this->m_img.copyTo(temp);
        cv::rectangle(temp, cv::Rect(top_left, bottom_right), color, 3);
        IplImage _img = temp;
        QImage qimg = IplImage2QImage(&_img);
        m_scene->clear();
        m_scene->addPixmap(QPixmap::fromImage(qimg));
        this->setScene(m_scene);
    }
    this->m_mutex.unlock();
}

void ImageView::clearSelected(){
    this->m_mutex.lock();
    if(!this->m_img.empty()){
        IplImage _img = this->m_img;
        QImage qimg = IplImage2QImage(&_img);
        m_scene->clear();
        m_scene->addPixmap(QPixmap::fromImage(qimg));
        this->setScene(m_scene);
    }
    this->m_mutex.unlock();
}

